package com.apimarket.security;

import com.alibaba.fastjson.JSON;
import com.apimarket.entity.Result;
import com.apimarket.entity.SysUser;
import com.apimarket.entity.kong.KeyAuthCredential;
import com.apimarket.entity.vo.SysUserMenuVo;
import com.apimarket.service.ConsumerService;
import com.apimarket.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

/**
 * @Description: 登录成功处理逻辑
 * 登录需要两个参数username,password,必须是POST请求
 * @Author ZXR
 * @Date 2021/7/20 14:32
 * @Version 1.0
 */

@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ConsumerService consumerService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //更新用户表上一次登录时间
        User userDetails=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser sysUser = sysUserService.selectByName(userDetails.getUsername());
        sysUser.setLastLoginTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUserService.update(sysUser);
        //此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
        //根据当前登录用户的用户id查找他有哪些菜单权限
        List<SysUserMenuVo> userMenusByUserId = sysUserService.findUserMenusByUserId(sysUser.getId());
        //获取这个用户的所有apikey
        List<KeyAuthCredential> consumerKeyAuth=null;
        try {
            consumerKeyAuth = consumerService.getConsumerKeyAuth(sysUser.getKongId());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if(consumerKeyAuth==null||consumerKeyAuth.size()<1){
            //如果登入用户没有密钥就创建一个密钥
            try {
                KeyAuthCredential keyAuthCredential = consumerService.generateKeyForConsumer(sysUser.getKongId());
                consumerKeyAuth.add(keyAuthCredential);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        //将所有的秘钥存到这个集合中
        List<String> apikeys=new ArrayList<>();
        if(consumerKeyAuth!=null){
            for(KeyAuthCredential key:consumerKeyAuth){
                apikeys.add(key.getKey());
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("menu",userMenusByUserId);
        map.put("keys",apikeys);
        map.put("kongId",sysUser.getKongId());
        //返回json数据
        //Result<List<SysUserMenuVo>> result=new Result<>(userMenusByUserId,200,"用户登录成功");
        Result<Map<String,Object>> result=new Result<>(map,200,"用户登录成功");
        //处理编码方式，防止中文乱码情况
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
